package org.javaboy.meeting.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Controller
public class VerificationCodeController {
    @RequestMapping("/getVerification")
    public void getVerification(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Random random = new Random();

        //设置宽，设置高，设置不透明
        BufferedImage img = new BufferedImage(110,40,BufferedImage.TYPE_INT_BGR);
        Graphics graphics=img.getGraphics();//GDI 图像绘制
        graphics.setColor(new Color(0x1f,0x1e,0x33));//设置背景颜色
        graphics.fillRect(0,0,110,40);//设置图像区域
        graphics.setFont(new Font("微软雅黑",Font.ITALIC,18));

        for (int i=0;i<5;i++){//画线
            graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            int x1=random.nextInt(90);
            int y1=random.nextInt(30);
            int x2=random.nextInt(90);
            int y2=random.nextInt(30);
            graphics.drawLine(x1,y1,x2,y2);//画线
        }

        String str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        char[] c =str.toCharArray();
        StringBuffer strb=new StringBuffer();

        for (int i=0;i<4;i++){
            int x = random.nextInt(c.length);
            strb.append(c[x]);
        }

        request.getSession().setAttribute("yzm",strb.toString().toLowerCase());

        for (int i=0;i<strb.toString().length();i++){
            graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            char z =strb.toString().charAt(i);
            graphics.drawString(z+"",10+(i*20),25);
        }
        graphics.dispose();//释放资源

        ImageIO.write(img,"png",response.getOutputStream());//图片输出
    }

}
